<template>
  <el-card>
    <!-- 搜索 -->
    <Search :model="searchForm" @search="getData" @reset="resetSearchForm">
      <SearchItem label="關鍵詞">
        <el-input v-model="searchForm.keyword" placeholder="產品名稱/條碼" clearable></el-input>
      </SearchItem>
    </Search>

    <!-- 新增|刷新 -->
    <ListHeader @create="handleCreate" @refresh="getData" v-permission="['product/create']" />

    <el-table :data="tableData" v-loading="loading">
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="產品名稱" :show-overflow-tooltip="true" />

      <el-table-column prop="cate" label="所屬分類" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ row.cate ? row.cate.name : '' }}

        </template>
      </el-table-column>
      <el-table-column label="產品圖">
        <template #default="{ row }">

          <el-image style="width: 100px; height: 50px" :src="row.banners.toString().split(',')[0]" hide-on-click-modal
            :preview-src-list="[row.banners.toString().split(',')[0]]" :preview-teleported="true" />
        </template>
      </el-table-column>
      <el-table-column prop="price" label="產品價格" />
      <el-table-column prop="cost" label="成本" />
      <el-table-column prop="num" label="產品庫存" />
      <el-table-column prop="type" label="產品類型">
        <template #default="{ row }">
          {{ row.type == 1 ? '預約' : '即時' }}
        </template>
      </el-table-column>
      <el-table-column prop="integral" label="餽贈積分" />
      <el-table-column label="是否推薦">
        <template #default="{ row }">
          <el-switch :modelValue="row.status" :active-value="1" :inactive-value="0" :loading="row.statusLoading"
            @change="handleStatusChange($event, row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否禁用">
        <template #default="{ row }">
          <el-switch :modelValue="row.statusdata" :active-value="0" :inactive-value="1" :loading="row.statusLoading"
            @change="handleStatusChange1($event, row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="創建時間" width="200" />
      <el-table-column label="操作" width="280" align="center">
        <template #default="scope">


          <!-- <el-button type="success" size="small" @click="handleSku(scope.row)">產品規格</el-button>   -->
          <el-button type="primary" size="small" @click="handleEdit(scope.row)"
            v-permission="['product/update']">修改</el-button>

          <el-popconfirm title="是否要删除？" confirmButtonText="確認" cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" size="small" v-permission="['product/delete']">删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev,pager,next" :total="total" :current-page="currentPage" :page-size="limit"
        @current-change="getData" />
    </div>

    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit" destroyOnClose >

      <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">

        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="基本參數" name="first">
            <el-form-item label="產品名" prop="name">
              <el-input v-model="form.name" placeholder="產品名" class="w-90"></el-input>
            </el-form-item>
            <el-form-item prop="category_id" label="分類">
              <el-select v-model="form.category_id" placeholder="選擇所屬分類">
                <el-option v-for="item in category_list" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="人手數量">
              <!-- <el-select v-model="form.admin_id" multiple placeholder="Select" style="width: 240px" >
                <el-option v-for="item in admindata" :key="item.username" :label="item.username" :value="item.id" />
              </el-select> -->
              <el-input v-model="form.admin_id" placeholder="人手數量" class="w-60"></el-input>
            </el-form-item>
            <el-form-item label="單位" prop="units">
              <el-input v-model="form.units" placeholder="單位" class="w-60"></el-input>
            </el-form-item>
            <!-- <el-form-item label="物資成本" prop="material_cost">
              <el-input v-model="form.material_cost" placeholder="物資成本" class="w-60"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="物資庫存" prop="material_num">
              <el-input v-model="form.material_num" placeholder="物資庫存" class="w-60"></el-input>
            </el-form-item> -->
            <el-form-item label="位置" prop="place">
              <el-input v-model="form.place" placeholder="位置" class="w-60"></el-input>
            </el-form-item>
            <el-form-item label="條碼" prop="borcode">
              <el-input v-model="form.borcode" placeholder="條碼" class="w-60"></el-input>
            </el-form-item>
            <el-form-item label="積分" prop="integral">
              <el-input v-model="form.integral" type="number" style="width:40%;" />
            </el-form-item>
            <el-form-item label="類型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1" border>預約</el-radio>
                <el-radio :label="2" border>即時</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="產品圖" prop="banners">
              <UploadImage :imgUrl="form.banners" @getUrl="getIdCardFrontUrl" :limit="5"></UploadImage>

            </el-form-item>

          </el-tab-pane>

          <el-tab-pane label="規格" name="second">


            <!-- <el-form-item label="规格类型" prop="is_spec">
              <el-radio-group v-model="form.is_spec">
               <el-radio :label="0" border>單規格</el-radio>
               <el-radio :label="1" border>多規格</el-radio>
              </el-radio-group>
            </el-form-item> -->
            
            <el-form-item label="價格" prop="price" v-if="form.is_spec == 0">
              <el-input v-model="form.price" type="number" style="width:40%;" />
            </el-form-item>
            <el-form-item label="成本" prop="cost" v-if="form.is_spec == 0">
              <el-input v-model="form.cost" type="number" style="width:40%;" />
            </el-form-item>
            <el-form-item label="庫存" prop="num" v-if="form.is_spec == 0">
              <el-input v-model="form.num" type="number" style="width:40%;" />
            </el-form-item>

            <!-- <el-form-item label="標籤"  v-if="form.is_spec == 0">
              <TagInput v-model="form.tag"></TagInput>
            </el-form-item> -->
          
            <!-- <Sku v-if="form.is_spec == 1"></Sku> -->

          </el-tab-pane>
          <el-tab-pane label="詳情" name="third">
            <el-form-item>
              <Editor v-model="form.content"></Editor>
            </el-form-item>

          </el-tab-pane>

        </el-tabs>

         
      </el-form>

    </FormDrawer>
  </el-card>
  <!-- <Spec ref="skuRef" @reload-data="getData"></Spec> -->
</template>

<script setup>
import { ref } from "vue"
import ListHeader from "@/components/ListHeader.vue";
import FormDrawer from "@/components/FormDrawer.vue";
import Search from "@/components/Search.vue";
import SearchItem from "@/components/SearchItem.vue";
import { useInitTable, useInitForm } from '@/composables/useCommon.js'
import UploadImage from '@/components/UploadImage.vue'
import { getList } from '@/api/category.js'
import { getproduct, del, update, create } from "@/api/product.js"
import Editor from "@/components/Editor.vue";
import { msg } from "@/composables/util"
import { ElNotification } from 'element-plus'
import {getadmin} from "@/api/manager.js"
import TagInput from "@/components/TagInput.vue"
// import Sku from "./Sku.vue"
const activeName = ref('first')
import Spec from "./Spec.vue"


const handleClick = (tab, event) => {
  console.log(tab, event)
}

const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  currentPage,
  total,
  limit,
  getData,
  handleDelete,
  handleStatusChange
} = useInitTable({
  searchForm: {
    keyword: ""
  },
  getList: getproduct,
  onGetListSuccess: (res) => {

    tableData.value = res.data
    total.value = res.total
    tableData.value.map(i => {
      if (i.inform == 1) {
        // msg(`產品id：${i.id}(${i.name})庫存不足`,'warning',5000)
        ElNotification({
          title: '提示',
          message: `產品id：${i.id}(${i.name})庫存不足`,
          type: 'warning',
          duration: 0
        })
      }
    })
  },
  delete: del,
  updateStatus: update
})

const {
  formDrawerRef,
  formRef,
  form,
  rules,
  drawerTitle,
  handleSubmit,
  handleCreate,
  handleEdit,
} = useInitForm({
  form: {
    name: "",
    price: 0,
    category_id: '',
    num: 1,
    cost: 0,
    units: '',
    banners: '',
    type: 1,
    integral: 0,
    content: '',
    is_spec: 0,
    place: '',
    borcode: '',
    statusdata: 0,
    material_cost:0,
    material_num:0,
    admin_id:'',
    tag:''
  },
  rules: {
    name: [{ required: true, message: '產品名稱不能為空', trigger: 'blur' }],
    category_id: [{ required: true, message: '分類不能為空', trigger: 'blur' }],
    price: [{ required: true, message: '價格不能為空', trigger: 'blur' }],
    num: [{ required: true, message: '庫存不能為空', trigger: 'blur' }],
    banners: [{ required: true, message: '產品圖不能為空', trigger: 'blur' }],
  },
  getData,
  update: update,
  create: create
})


const handleStatusChange1 = (e, d) => {
  update(d.id, { statusdata: e }).then(res => {
    msg('狀態修改成功！')
    getData();
  })
}


const category_list = ref([])
getList().then(res => category_list.value = res)

const getIdCardFrontUrl = (url) => {
  form.banners = url;
};

// const admindata=ref(null)
// const getManager=()=>{
//   getadmin().then(res=>{
//     admindata.value=res.data.data
//   })
// }

// getManager()

//設置規格
const skuRef=ref(null)
const handleSku=(row)=>skuRef.value.open(row)
</script>
